﻿Public Class NumberTextBox
    Inherits TextBox

    Shared Sub New()
        TextBox.TextProperty.OverrideMetadata(GetType(NumberTextBox), New FrameworkPropertyMetadata("0"))
    End Sub

    Public Shared ReadOnly ValueProperty As DependencyProperty = _
        DependencyProperty.Register( _
            "Value", GetType(Double), GetType(NumberTextBox), _
            New FrameworkPropertyMetadata( _
                0.0#, _
                Sub(d, e) CType(d, NumberTextBox).OnValueChanged(CType(e.OldValue, Double), CType(e.NewValue, Double))))

    Public Property Value As Double
        Get
            Return CType(GetValue(ValueProperty), Double)
        End Get
        Set(ByVal value As Double)
            SetValue(ValueProperty, value)
        End Set
    End Property

    Private Sub OnValueChanged(oldValue As Double, newValue As Double)
        If Not IsFocused Then
            Text = Value.ToString("R")
        End If
    End Sub

    Protected Overrides Sub OnTextChanged(e As System.Windows.Controls.TextChangedEventArgs)
        MyBase.OnTextChanged(e)

        Dim s = Text
        Dim d = Value
        If Not Double.TryParse(s, d) Then Return
        If Double.IsInfinity(d) Or Double.IsNaN(d) Then Return
        Value = d
    End Sub

    Protected Overrides Sub OnLostFocus(e As System.Windows.RoutedEventArgs)
        MyBase.OnLostFocus(e)
        Text = Value.ToString("R")
    End Sub

End Class
